package com.ihteima.interceptor;

import com.ihteima.utils.JwtUtil;
import com.ihteima.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

/**
 * ClassName: JwtTokenUserInterceptor
 * Package: com.ihteima.interceptor
 * Description:
 *
 * @Auther gongkaiming
 * @Create 2025/10/26 18:39
 * @Version 1.0
 */
@Component
@Slf4j
public class JwtTokenUserInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        String token = request.getHeader("Authorization");
        try {
            log.info("jwt校验:{}", token);
            Map<String, Object> claims = JwtUtil.parseToken(token);
            Long Id = Long.valueOf(claims.get("id").toString());
            log.info("当前用户id：", Id);
            ThreadLocalUtil.set(Id);
            return true;
        } catch (Exception e) {
            throw new RuntimeException(e);
        } 
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }
}
